import { glob } from "glob";
import { basename, dirname, extname, format, join, relative } from "path";
import fs from "node:fs";
import {normalizePath} from 'vite'
import { buildSync } from "esbuild";
export function winPath(path: string) {
  const isExtendedLengthPath = /^\\\\\?\\/.test(path);
  if (isExtendedLengthPath) {
    return path;
  }
  return path.replace(/\\/g, "/");
}

const getRoutes = (items,pid) => {
  let i = 0;
  const flat = (items,pid) => {
    let list:any = [];
    items.forEach((item) => {
      i++;
      const route = { path: item?.path,element:item?.element, id: `${i}`, pid: `${pid}` };
      list.push(route);
      if (item?.children?.length) {
        list = list.concat(flat(item?.children, i));
      }
    });
    return list
  };
  return  flat(items,pid)
};
export default function myPlugin() {
  const path=join(process.cwd(),'./src/routes.tsx')
  return {
    name: "my-plugin",
    async configureServer(devServer) {
    
        const {
          watcher,
        } = devServer;
        
        watcher.on("change", async (eventName) => {
         
            const watchFile=normalizePath(eventName)
            const pathRoutes=normalizePath(path)
            if(watchFile===pathRoutes){
              const outPath=normalizePath(join(process.cwd(),'./src/.qps/plugin-router/routes-catech.js'))
              buildSync({
              entryPoints:[pathRoutes],
              outfile:outPath
             })

                
              const routes= (await import(`file://${winPath(outPath)}`)).default
              console.log(outPath,routes)
              const list=getRoutes(routes,0)
              console.log(pathRoutes,"===>",list)
              const path=join(process.cwd(),'./src/.qps/plugin-router/routes.ts')
              let routeComponents=''
              list.forEach(item=>{
                  routeComponents+=`${item.id}:React.lazy(() => import('${item?.element}')),`
           })
            
            const str=`//@ts-nocheck
            import React from 'react';
            
            export  function getRoutes() {
              const routes = ${JSON.stringify(list)} as const;
              return {
                routes,
                routeComponents:{ ${routeComponents}},
              };
            }
           `
             fs.writeFileSync(path,str)
             if(fs.existsSync(outPath)){
               fs.unlinkSync(outPath)    
             }
            }
          
        })
     
    },
    buildStart(options){
        console.log("===>",options)
    }
    
  };
}
